package com.aracky.system.service.impl;

import com.aracky.common.exception.BaseException;
import com.aracky.common.util.ComUtil;
import com.aracky.common.util.ConvertUtil;
import com.aracky.common.vo.LoginUserVO;
import com.aracky.system.mapper.SysUserMapper;
import com.aracky.system.model.entity.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zengzhiping
 * @BelongsPackage com.aracky.system.service.impl
 * @CreateTime 2022-07-15
 * @Description
 */
@Service
public class LoginUserServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> lambdaQuery = Wrappers.<SysUser>lambdaQuery().eq(SysUser::getLoginName, username);
        SysUser user = sysUserMapper.selectOne(lambdaQuery);

        if (user == null) {
            throw new BaseException("当前用户不存在");
        }
        LoginUserVO loginUserVO = ConvertUtil.sourceToTarget(user, LoginUserVO.class);
        //获取权限
        List<GrantedAuthority> auths = new ArrayList<>();
        loginUserVO.setAuthorities(auths);

        //获取当前用户角色
        List<String> roleKey = sysUserMapper.findRoleKey(loginUserVO.getUserId());
        if (ComUtil.isNotNullList(roleKey)) {
            loginUserVO.setRoleList(roleKey);
        }
        return loginUserVO;
    }
}
